import React, {Component} from 'react';
import {Button, Form, Row, Col, DatePicker, Table, Pagination, Input, Select,Modal,Radio} from 'antd';
import moment from 'moment';
import {statistics, excel} from "../value";
import app from '../AppMethod';
import {config} from "../config";
import {Consumer} from "../store";
import '../css/goodManage.css';

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const RadioGroup=Radio.Group;

class goodManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            currentGoodType: 1,
            goodData: [
                {
                    good_id: '0001',
                    good_name: '龟苓膏',
                    good_type: 1,
                    good_picture: '222.png',
                    good_price: '10',
                    good_stock: 100,
                    good_shop_num: 45,
                    good_status: 0
                },
                {
                    good_id: '0002',
                    good_name: '龟苓膏',
                    good_type: 2,
                    good_picture: '222.png',
                    good_price: '10',
                    good_stock: 100,
                    good_shop_num: 45,
                    good_status: 1
                }
            ],
            selectedRowKeys: [],
            visible:false,
            value:1
        }
    };

    columns = [
        {
            title: '商品名',
            dataIndex: 'good_name'
        },
        {
            title: '分类',
            dataIndex: 'good_type',
            render: good_type => {
                let text = '';
                if (good_type == 1) {
                    text = '甜品';
                } else if (good_type == 2) {
                    text = '蛋糕';
                } else {
                    text = '其它';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '图片',
            dataIndex: 'good_picture'
        },
        {
            title: '价格',
            dataIndex: 'good_price'
        },
        {
            title: '库存',
            dataIndex: 'good_stock',
            sorter: true,
        },
        {
            title: '销量',
            dataIndex: 'good_shop_num',
            sorter: true,
        },
        {
            title: '状态',
            dataIndex: 'good_status',
            sorter: true,
            render: good_status => {
                let text = '';
                if (good_status == 0) {
                    text = '已下架';
                } else if (good_status == 1) {
                    text = '售卖中';
                }
                return (
                    <span>
                        {
                            good_status == 1 ?
                                <span style={{color: '#008000'}}>{text}</span> :
                                <span>{text}</span>
                        }
                    </span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        {
                            data.good_status==0?
                                <span style={{color: '#1890ff', cursor: 'pointer'}}>上架</span>
                                :
                                <span style={{color: 'red', cursor: 'pointer'}}>下架</span>
                        }
                        <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleCancel(data.car_id)}>{'编辑'}</span>
                        <span style={{color: 'red', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleFinish(data.car_id)}>{'删除'}</span>
                    </span>
                )
            }
        }
    ];

    render() {
        const {currentGoodType, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div style={{height: '100%'}}>
                <div className="goodManageHeader"></div>
                <div className="goodManageListContainer">
                    <div className="goodManageListContainerLeft">
                        <div className="goodManageListContainerType">
                            <div className={`goodManageListContainerTypeItem ${currentGoodType == 1 ? 'active' : ''}`}
                                 onClick={() => this.handleChooseGoodType(1)}>
                                全部
                            </div>
                            <div className={`goodManageListContainerTypeItem ${currentGoodType == 2 ? 'active' : ''}`}
                                 onClick={() => this.handleChooseGoodType(2)}>
                                甜品
                            </div>
                            <div className={`goodManageListContainerTypeItem ${currentGoodType == 3 ? 'active' : ''}`}
                                 onClick={() => this.handleChooseGoodType(3)}>
                                蛋糕
                            </div>
                            <div className={`goodManageListContainerTypeItem ${currentGoodType == 4 ? 'active' : ''}`}
                                 onClick={() => this.handleChooseGoodType(4)}>
                                小吃
                            </div>
                        </div>
                    </div>
                    <div className="goodManageListContainerRight">
                        <div className="goodManageListContainerLeftTitle">
                            商品管理/添加商品
                        </div>
                        <Row className="goodManageListContainerSearch">
                            <Button type="primary" ghost className={'btnMarinLeft'}>发布商品</Button>
                            <Button type="primary" ghost className={'btnMarinLeft'}>批量上架</Button>
                            <Button type="danger" ghost className={'btnMarinLeft'}>批量下架</Button>
                            <Button type="danger" ghost className={'btnMarinLeft'}>批量删除</Button>
                            <Button type="primary" className={'btnMarinLeft'}>导入</Button>
                            <Button type="primary" className={'btnMarinLeft'} onClick={()=>this.handleCancel(true)}>批量设置</Button>
                            <div className="goodManageListContainerInputName">
                                商品名称：<Input placeholder="请输入"/>
                            </div>
                            <div className="goodManageListContainerInputStatus">
                                状态：
                                <Select placeholder="请选择" style={{width: 100}}>
                                    <Option value="0">全部</Option>
                                    <Option value="1">售卖中</Option>
                                    <Option value="2">已下架</Option>
                                </Select>
                            </div>
                            <Button type="primary" style={{marginLeft: 40}}>搜索</Button>
                        </Row>
                        <div className="goodManageListTableContainer">
                            <Table
                                columns={this.columns}
                                rowKey={record => record.good_id}
                                loading={this.state.loading}
                                dataSource={this.state.goodData}
                                pagination={false}
                                rowSelection={rowSelection}
                            >
                            </Table>
                        </div>
                        <Row style={{marginTop: '20px'}}>
                            <Col span={12} style={{fontSize: '15px'}}>
                                共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current}
                                / {this.state.allPage}
                                页
                            </Col>
                            <Col span={12} style={{textAlign: 'right'}}>
                                <Pagination {...this.state.pagination} hideOnSinglePage={false}
                                            onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}/>
                            </Col>
                        </Row>
                    </div>
                </div>
                <div>
                    <Modal
                        title="批量设置"
                        visible={this.state.visible}
                        onOk={()=>this.handleConfirmSetting()}
                        onCancel={()=>this.handleCancel(false)}
                    >
                        <Row className="goodManageSetting">
                            <div style={{color:'red'}}>销售端</div>
                            <div style={{marginLeft:20}}>
                                <RadioGroup onChange={this.handleSettingOnChange} value={this.state.value} style={{paddingTop:0}}>
                                    <Radio value={1}>所有</Radio>
                                    <Radio value={2}>外卖</Radio>
                                    <Radio value={3}>店内</Radio>
                                </RadioGroup>
                            </div>
                        </Row>
                    </Modal>
                </div>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "订单数据统计"});
        let date_end = moment(new Date()).format('YYYY-MM-DD');
        let date_start = app.getBeforeDate(4);
        let data = {page: 1, size: 5, date_start: date_start, date_end: date_end};
        //this.handleGetOrderList(data);
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    handleCancel(visible){
        this.setState({visible:visible});
    }

    /**
     * 处理全选事件
     * @param selectedRowKeys
     */
    onSelectChange = (selectedRowKeys) => {
        this.setState({selectedRowKeys});
    };

    /**
     * 处理批量设置单选事件
     * @param e
     */
    handleSettingOnChange=(e)=>{
        this.setState({value:e.target.value});
    };

    /**
     * 处理确认批量设置事件
     */
    handleConfirmSetting(){

    }

    /**
     * 处理当担商品类型选择变化事件
     * @param index
     */
    handleChooseGoodType(index) {
        this.setState({currentGoodType: index});
    }

    handleChangeImg(id) {
        let orderData = this.state.orderData;
        for (let i = 0; i < orderData.length; i++) {
            if (id == orderData[i].orderId) {
                orderData[i].show = !orderData[i].show;
            }
        }
        this.setState({orderData: orderData});
    }

    /**
     * 获取订单数据列表
     * @param data
     */
    handleGetOrderList(data = {page: 1, size: 5, date_start: '2018-06-01', date_end: '2018-06-05'}) {
        this.setState({loading: true});
        app.post(statistics.TOTAL_OUTPUTSTATISTICS, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                this.setState({allPage, pagination});
                let employeeData = result.data.dataSet;
                let employeeData1 = [];
                let employeeData2 = [
                    ['time', '下单数', '未配货', '已配货', '配送中', '已配送'],
                ];
                for (let i = 0; i < employeeData.length; i++) {
                    employeeData[i].date_id = employeeData[i].date_id == null ? '' : moment(employeeData[i].date_id).format('YYYY-MM-DD');
                    employeeData1 = [];
                    employeeData1.push(employeeData[i].date_id);
                    employeeData1.push(employeeData[i].total_output);
                    employeeData1.push(employeeData[i].total_unpick);
                    employeeData1.push(employeeData[i].total_pick);
                    employeeData1.push(employeeData[i].total_send);
                    employeeData1.push(employeeData[i].total_finish);
                    employeeData2.push(employeeData1);
                }
                let rawMill = this.state.rawMill;
                rawMill.dataset.source = employeeData2;
                this.setState({rawMill, data: employeeData, loading: false});
            } else {
                let rawMill = this.state.rawMill;
                rawMill.dataset.source = [['time', '下单数', '未配货', '已配货', '配送中', '已配送']];
                this.setState({rawMill, data: [], loading: false});
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination});
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 根据条件搜索订单列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end
        };
        this.setState({searchData: tempData});
        let searchData = tempData;
        searchData.page = 1;
        searchData.size = 5;
        this.handleGetOrderList(searchData);
    };

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        let date_end = moment(new Date()).format('YYYY-MM-DD');
        let date_start = app.getBeforeDate(4);
        let data = {page: 1, size: 5, date_start: date_start, date_end: date_end};
        this.handleGetOrderList(data);
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleGetOrderList(data);
    };

    /**
     * 处理导出Excel事件
     * @param value
     */
    handleExport(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end
        };
        let params = app.getParams(tempData);
        if (params.length > 0) {
            window.location.href = config.serverUrl + excel.EXPORT_OUTPUTSTATISTICS + '?' + params;
        } else {
            app.alert('请选择时间范围', 'error', 3);
        }
    }
};

const GoodManages = Form.create()(goodManage);
export default prop => (
    <Consumer>
        {
            props => (
                <GoodManages {...prop} {...props}/>
            )
        }
    </Consumer>
);